<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChRoomInviteActiveRoom;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;

class ChRoomInviteActiveRoomMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChRoomInviteActiveRoom::class;
    }


    public function getActiveRoomListByRobotId($schemeId,$schemeType,$robotId): \Hyperf\Collection\Collection
    {
        return Db::table('ch_room_invite_active_room as a')
            ->select(['a.*'])
            ->join('ch_room as b','a.room_wxid','=','b.room_wxid')
            ->join('ch_room_robot as c','b.id','=','c.room_id')
            ->where('a.scheme_id',$schemeId)
            ->where('a.scheme_type',$schemeType)
            ->where('c.robot_id',$robotId)
            ->get();
    }

    /**
     * 获取生效群列表
     * @param array $params
     * @return \Hyperf\Contract\LengthAwarePaginatorInterface
     */
    public function getActiveRoomPageList(array $params): \Hyperf\Contract\LengthAwarePaginatorInterface
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $query = $this->model::query()
            ->with(['robot'=>function ($query) {
                $query->select(['id','nickname','avatar','user_id']);
            },'room' => function ($query) {
                $query->select(['id','room_name','room_member_count','room_wxid']);
            }]);
        $params['is_page_list'] = 1;
        return $this->handleSearch($query,$params)->paginate((int)$pageSize);
    }

    public function checkSubstituteRoomExists(int $schemeId,int $schemeType)
    {
        return $this->model::query()
            ->where('scheme_id',$schemeId)
            ->where('scheme_type',$schemeType)
            ->where('is_substitute',1)
            ->exists();
    }

    /**
     * 获取邀请生效群微信ID
     * @param array $params
     * @return array
     */
    public function getInviteActiveRoomWxid(array $params): array
    {
        $query = $this->model::query()
            ->select(['id','room_wxid'])
            ->with(['room'=>function ($query) {
                $query->select(['id','room_wxid','room_member_count']);
            }]);
        return $this->handleSearch($query,$params)->orderBy('sort')->get()->toArray();
    }

    /**
     * 获取进粉中的群
     * @param int $robotId
     * @param int $schemeId
     * @param int $schemeType
     * @return ChRoomInviteActiveRoom|Builder|null
     */
    public function getInviteRoomInFanIn(int $robotId,int $schemeId,int $schemeType): ChRoomInviteActiveRoom|Builder|null
    {
        $query = $this->model::query()
            ->with(['room'=>function ($query) {
                $query->select(['id','room_member_count']);
            }]);
        $params['robot_id'] = $robotId;
        $params['scheme_id'] = $schemeId;
        $params['scheme_type'] = $schemeType;
        $params['status'] = 1;
        return $this->handleSearch($query,$params)->orderBy('sort')->first();
    }

    public function getNextInviteRoomInFanIn(int $robotId,int $schemeId,int $schemeType): ChRoomInviteActiveRoom|Builder|null
    {
        $query = $this->model::query();
        $params['robot_id'] = $robotId;
        $params['scheme_id'] = $schemeId;
        $params['scheme_type'] = $schemeType;
        $params['status'] = 1;
        $params['room_status'] = 1;
        return $this->handleSearch($query,$params)->first();
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        if(!empty($params['scheme_id'])){
            $query->where('scheme_id',$params['scheme_id']);
        }

        if(!empty($params['scheme_type'])){
            $query->where('scheme_type',$params['scheme_type']);
        }

        if(!empty($params['robot_id'])){
            $robotId = $params['robot_id'];
            $query->whereHas('room.robots',function ($query) use ($robotId){
                $query->where('robot_id',$robotId);
            });
        }

        if(!empty($params['robot_keyword'])){
            $query->whereHas('robot',function ($query) use ($params){
                $query->where('nickname','like',"%{$params['robot_keyword']}%");
            });
        }

        if(!empty($params['room_keyword'])){
            $query->whereHas('room',function ($query) use ($params){
                $query->where('room_name','like',"%{$params['room_keyword']}%");
            });
        }

        if(isset($params['gender']) && filled($params['gender'])){
            $gender = json_encode($params['gender']);
            $query->whereRaw("JSON_CONTAINS(genders,{$gender})");
        }

        if(isset($params['room_status']) && filled($params['room_status'])){
            if($params['room_status'] == 0){
                $query->whereHas('room',function ($query) use ($params){
                    $query->where('room_member_count','<',$params['group_user_count']);
                });
            }else{
                $query->whereHas('room',function ($query) use ($params){
                    $query->where('room_member_count','>=',$params['group_user_count']);
                });
            }
        }

        if(isset($params['status']) && filled($params['status'])){
            $query->where('status',$params['status']);
        }else{
            if(!isset($params['is_page_list'])){
                $query->where('status','<>',2);
            }
        }

        return $query;
    }
}